import { Body, Controller, Delete, Get, Headers, Inject, LoggerService, Param, ParseIntPipe, Patch, Post, Query, Req, UnauthorizedException, UseFilters } from '@nestjs/common';
import { UserService } from './user.service';
import { User } from './user.entity';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { getUserDto } from './dto/get-user.dto';
import { TypeormFilter } from '../../filters/typeorm.filter';
import { CreateUserPipe } from './pipes/create-user/create-user.pipe';
import { CreateUserDto } from './dto/create-user.dto';
import { wrapperResponse } from '../../utils';
// import { AuthGuard } from 'src/auth/auth.guard';

@Controller('user')
@UseFilters(new TypeormFilter())
export class UserController {
  // private logger = new Logger(UserController.name)
  constructor(
    private userServie: UserService,
    @Inject(WINSTON_MODULE_NEST_PROVIDER) private readonly logger: LoggerService
  ) {
    // this.logger.log('UserController init')
  }

  @Get('/info')
  getUserByToken(@Req() req){
    return wrapperResponse(
      this.userServie.findByUsername(req.user.username),
      '获取用户信息成功'
    );
  }

  @Get()
  getUsers(@Query() query: getUserDto): any {
    // console.log("🚀 ~ UserController ~ getUsers ~ query:", query)

    return this.userServie.findAll(query);
  }

  @Get('/profile')
  getUserProfile(@Query('id', ParseIntPipe) id: any): any {
    // console.log("🚀 ~ UserController ~ getUserProfile ~ id:", id, typeof id)
    return this.userServie.findProfile(id);
  }

  @Post()
  addUser(@Body(CreateUserPipe) dto: CreateUserDto): any {
    const user = dto as User;
    return this.userServie.create(user);
  }

  @Get('/:id')
  getUser(): any {
    return 'getUser'
  }

  @Patch('/:id')
  updateUser(@Body() dto: any, @Param('id') id: number, @Headers('Authorization') headers: any): any {
    if (id === headers){
      const user = dto as User;
      // console.log("🚀 ~ UserController ~ updateUser ~ user:", user)
      return this.userServie.update(id, user);
    } else {
      throw new UnauthorizedException()
    }

  }

  @Delete('/:id')
  removeUser(@Param('id') id: number): any {
    // todo 传递参数id
    return this.userServie.remove(id);
  }


  @Get('/logs')
  getUserLogs(): any {
    return this.userServie.findUserLogs(2);
  }

  @Get('logsByGroup')
  async getLogsByGroup(): Promise<any> {
    const res = await this.userServie.findLogsByGroup(2);
    return res.map((o) => ({
      result: o.result,
      count: o.count,
    }))
  }
}
